<script setup>
import { storeToRefs } from 'pinia';

useHead({
    title: 'HLS: Список нарядов',
})

const etapStore = useOneEtap();
// const { one_etap } = storeToRefs(etapStore);
const { setEtap } = etapStore;

const urlHome = useUrl();

const user = useCookie('user');
const mpp = useCookie('mpp');

if (!mpp.value) {
    navigateTo('/login');
}

const counter = useStoreCounter();
const router = useRouter();

const sort_by = ref('');
const naryad_search = ref('');

const modal_number_nar = ref('');
const modal_stu_nar = ref('');
const modal_patient_nar = ref('');

const isOpen = ref(false);

const pend = ref('')
pend.value = false;

const { sort_list } = useSortList();

const idkvModal = ref(0);

defineShortcuts({
    meta_k: {
        usingInput: true,
        handler: () => { isOpen.value = !isOpen.value }
    },
    escape: {
        usingInput: true,
        whenever: [isOpen],
        handler: () => { isOpen.value = false }
    },
    meta_g: {
        usingInput: true,
        whenever: [isOpen],
        handler: () => { isOpen.value = false }
    },

})

function removeAnElement(array, index) {
    if (index === 0) {
        array.shift();
    } else {
        array.splice(index, 1);
    }
}

const { pending, data: narList, error, refresh: narListUpdate } = await useLazyFetch(`${urlHome.value}lab/nar_list/`, {
    query: {
        mpp: mpp.value,
        status: "open"
    }
})


async function moveTo(id, sdl, index) {
    const { data: next_etap_status } = await useAsyncData('next_etap_status', () => $fetch(urlHome.value + 'naryad/next_etap/' + id + '/' + sdl + '/True' + '/' + mpp.value))
    if (next_etap_status._rawValue.status == 'ok') {
        removeAnElement(narList.value, index);
    }
    if (next_etap_status._rawValue.status == 'exist') {
        alert('Такой этап уже есть');
        removeAnElement(narList.value, index);
    }
    counter.counterMoveNaryadToOther();
    return;
}


const { data: uslModal } = await useLazyFetch(`${urlHome.value}lab/pl_uslp_list`, {
    immediate: false,
    watch: [idkvModal],
    query: {
        idkv: idkvModal,
    }
})


async function getUsl(idkv, nkv, stu, fam, im, ot) {
    idkvModal.value = idkv
    console.log(idkv, idkvModal.value)
    modal_number_nar.value = nkv;
    modal_stu_nar.value = stu;
    modal_patient_nar.value = fam + ' ' + im + ' ' + ot;
    isOpen.value = true;
    return;
}

function toNaryad(index, id) {
    setEtap(narList.value[index]);
    router.push('/lab/naryad/' + id)
}

function sortNaryadList(sortBy) {
    switch (sortBy) {
        case 'dnaz_etap_inc':
            narList.value.sort(function (a, b) {
                return (new Date(a.dou)) - (new Date(b.dou));
            });
            break;
        case 'dnaz_etap_desc':
            narList.value.sort(function (a, b) {
                return (new Date(b.dou)) - (new Date(a.dou));
            });
            break;
        case 'stu_inc':
            narList.value.sort(function (a, b) {
                return a.stu - b.stu;
            });
            break;
        case 'stu_desc':
            narList.value.sort(function (a, b) {
                return b.stu - a.stu;
            });
            break;
    }
    return;
}

function resetSearch() {
    naryad_search.value = '';
    sort_by.value = '';
    narListUpdate();
}


function refresh_all() {
    resetSearch();
    narListUpdate();
}

</script>

<template>
    <div>
        <div
            class="px-2 py-2 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-3 2xl:grid-cols-3 sm:flex md:flex lg:flex xl:flex 2xl:flex sm:gap-4">
            <UButton label="Обновить" @click="refresh_all" />
            <UInput color="green" placeholder="Фамилия пациента" v-model="naryad_search" />
            <USelect color="green" v-model="sort_by" :options="sort_list" option-attribute="name"
                @change="sortNaryadList(sort_by)" />
            <UButton v-if="naryad_search != '' || sort_by != ''" label="Очистить" @click="resetSearch()" />
        </div>
        <div v-if="pend">
            <LoadFetchAnimation></LoadFetchAnimation>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3" v-auto-animate>
            <div v-for="( item, index ) in  narList" :key="item.nkv">
                <div v-show="((item.patient.fam).toUpperCase()).includes((naryad_search).toUpperCase())">
                    <NaryadListNaryadCard :getUsl="getUsl" :item="item" :toNaryad="toNaryad" :moveTo="moveTo"
                        :index="index" />
                </div>
            </div>
        </div>
        <UModal v-model="isOpen" :ui="{ base: 'max-w-4xl', width: '' }">
            <UCard :ui="{ ring: '', divide: 'divide-y divide-gray-100 dark:divide-gray-800' }">
                <template #header>
                    <div
                        class="grid grid-cols-1 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-3 2xl:grid-cols-3 sm:flex md:flex lg:flex xl:flex 2xl:flex sm:gap-4">
                        <div class="text-2xl ">Наряд : <b>{{ modal_number_nar }}</b></div>
                        <div class="text-2xl ">Сумма : <b>{{ modal_stu_nar }} ₽</b></div>
                        <div class="text-1xl align-middle">Пациент : {{ modal_patient_nar }}</div>
                    </div>
                </template>
                <div class="overflow-x-auto relative">
                    <div class="flex flex-row w-full">
                        <div class="basis-1/4"><b>Код</b></div>
                        <div class="basis-1/4"><b>Кол-во</b></div>
                        <div class="basis-1/4 text-right"><b>Цена</b></div>
                        <div class="basis-1/4 text-right"><b>Сумма</b></div>
                    </div>
                    <hr>
                    <div v-for="( item, index ) in  uslModal" :key="item.kusl">
                        <div>
                            <div class="flex flex-row w-full">
                                <div class="basis-1/4"><b>{{ item.kusl }}</b></div>
                                <div class="basis-1/4"><b>{{ item.kol }}</b></div>
                                <div class="basis-1/4 text-right"><b>{{ (item.price).toLocaleString() }} ₽</b></div>
                                <div class="basis-1/4 text-right"><b>{{ (item.stu).toLocaleString() }} ₽</b></div>
                            </div>

                            <div class="break-words">{{ item.nusl }}</div>
                        </div>
                        <hr>
                    </div>
                </div>

                <template #footer>
                    <UButton @click="isOpen = false" label="Закрыть" />
                </template>
            </UCard>
        </UModal>
    </div>
</template>
